<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\MoneyTransaction;
use App\Models\MoneyCategory;
use App\Models\MembershipCode;
use App\Services\OcrService;
use App\Services\AudioTranscribeService;
use App\Services\WechatAvatarService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use App\Jobs\ProcessWechatMessageJob;
use App\Jobs\ProcessFreeMembershipJob;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class WechatController extends Controller
{
    protected $wxapp;

    public function __construct(Application $app)
    {
        $this->wxapp = new Application(config('wechat.official_account.default'));
//       (new \EasyWeChat\OfficialAccount\Application(config('wechat.official_account.default')))->getAccessToken()->refresh();
    }

    public function bind()
    {
        $redirectUrl = route('wechat.callback');
        session(['wechat_bind_redirect' => url()->previous()]);
        $oauth = $this->wxapp->getOauth();
        return redirect($oauth->redirect($redirectUrl));
    }

    /**
     * 微信授权登录
     */
    public function login(Request $request)
    {
        $redirectUrl = route('wechat.login.callback');
        // 保存用户访问的原始页面URL，以便登录后跳转回去
        session(['login_redirect' => url()->previous() !== route('wechat.login.callback') ? url()->previous() : route('home')]);
        $oauth = $this->wxapp->getOauth();
        return redirect($oauth->redirect($redirectUrl));
    }

    public function callback()
    {
        try {
            // 使用Laravel-WeChat提供的方法获取OAuth实例
            $oauth = $this->wxapp->getOauth();
            $user = $oauth->userFromCode(request('code'));

            // 更新用户的 openid
            Auth::user()->update([
                'openid' => $user->getId()
            ]);

            session()->put('success_msg', '微信绑定成功！');
            return redirect(session()->pull('url.intended', route('home')));
        } catch (\Exception $e) {
            session()->put('error_msg', '微信绑定失败，请重试');
            return redirect(route('user.profile'));
        }
    }

    /**
     * 微信授权登录回调
     */
    public function loginCallback(Request $request)
    {
        try {
            // 使用Laravel-WeChat提供的方法获取OAuth实例
            $oauth = $this->wxapp->getOauth();
            $wxUser = $oauth->userFromCode(request('code'));

            // 根据openid查找用户
            $user = User::where('openid', $wxUser->getId())->first();

            if ($user) {
                // 用户存在，直接登录，设置记住登录（与记住登录功能保持一致的有效期）
                Auth::login($user, true);
                session()->put('success_msg', '微信登录成功！');
                return redirect(session('login_redirect', route('home')));
            } else {
                // 用户不存在，保存openid到session，跳转到绑定页面
                session(['wechat_temp_openid' => $wxUser->getId()]);
                session(['wechat_temp_user_info' => [
                    'nickname' => $wxUser->getNickname(),
                    'avatar' => $wxUser->getAvatar(),
                ]]);
                return redirect(route('wechat.bind'));
            }
        } catch (\Exception $e) {
            Log::error('微信授权登录失败：' . $e->getMessage());
            session()->put('error_msg', '微信授权登录失败，请重试');
            return redirect(route('login'));
        }
    }

    /**
     * 显示微信绑定页面
     */
    public function showBindPage()
    {
        // 检查是否有微信用户信息
        if (!session('wechat_temp_user_info')) {
            return redirect(route('login'))->with('error_msg', '请先进行微信授权');
        }

        return view('auth.wechat-bind');
    }

    /**
     * 显示微信登录绑定页面
     */
    public function showLoginBindPage()
    {
        // 检查是否有微信用户信息
        if (!session('wechat_temp_user_info')) {
            return redirect(route('login'))->with('error_msg', '请先进行微信授权');
        }

        return view('auth.wechat-login-bind');
    }

    /**
     * 显示微信注册绑定页面
     */
    public function showRegisterBindPage()
    {
        // 检查是否有微信用户信息
        if (!session('wechat_temp_user_info')) {
            return redirect(route('login'))->with('error_msg', '请先进行微信授权');
        }

        return view('auth.wechat-register-bind');
    }

    /**
     * 处理微信登录绑定
     */
    public function submitLoginBind(Request $request)
    {
        try {
            // 验证请求数据
            $request->validate([
                'name' => 'required|string',
                'password' => 'required|string',
            ], [
                'name.required' => '用户名不能为空',
                'password.required' => '密码不能为空',
            ]);

            // 检查是否有微信用户信息
            if (!session('wechat_temp_openid') || !session('wechat_temp_user_info')) {
                return response()->json([
                    'success' => false,
                    'message' => '微信授权信息已过期，请重新授权'
                ], 400);
            }

            // 尝试登录
            $credentials = [
                'name' => $request->name,
                'password' => $request->password
            ];

            if (Auth::attempt($credentials, true)) {
                 $user = Auth::user();
                 $wechatUserInfo = session('wechat_temp_user_info');
                 $avatarService = new WechatAvatarService();

                 // 准备更新数据
                 $updateData = [
                     'openid' => session('wechat_temp_openid')
                 ];

                 // 处理头像：如果用户是默认头像，则替换为微信头像
                 if ($avatarService->isDefaultAvatar($user) && !empty($wechatUserInfo['avatar'])) {
                     $localAvatarPath = $avatarService->downloadAndSaveWechatAvatar(
                         $wechatUserInfo['avatar'],
                         $user->id
                     );

                     if ($localAvatarPath) {
                         // 删除旧头像
                         if ($user->avatar) {
                             $avatarService->deleteOldAvatar($user->avatar);
                         }
                         $updateData['avatar'] = $localAvatarPath;
                     }
                 }

                 // 处理昵称：如果nickname和name一致，则使用微信昵称
                 if ($avatarService->shouldUseWechatNickname($user, $wechatUserInfo['nickname'])) {
                     $updateData['nickname'] = $wechatUserInfo['nickname'];
                 }

                 // 绑定微信信息
                 $user->update($updateData);

                // 清除临时session
                session()->forget(['wechat_temp_openid', 'wechat_temp_user_info']);

                $request->session()->regenerate();

                return response()->json([
                    'success' => true,
                    'message' => '登录成功！微信账号绑定完成',
                    'redirect_to' => session('login_redirect', route('home'))
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => '用户名或密码错误'
            ], 400);

        } catch (\Exception $e) {
            Log::error('微信登录绑定失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '登录失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 处理微信注册绑定
     */
    public function submitRegisterBind(Request $request)
    {
        try {
            // 验证请求数据
            $request->validate([
                'name' => 'required|string|min:2|max:255|unique:users,name',
                'password' => 'required|string|min:6|confirmed',
            ], [
                'name.required' => '用户名不能为空',
                'name.min' => '用户名至少2个字符',
                'name.max' => '用户名不能超过255个字符',
                'name.unique' => '该用户名已被注册',
                'password.required' => '密码不能为空',
                'password.min' => '密码至少6位',
                'password.confirmed' => '两次输入的密码不一致',
            ]);

            // 检查是否有微信用户信息
            if (!session('wechat_temp_openid') || !session('wechat_temp_user_info')) {
                return response()->json([
                    'success' => false,
                    'message' => '微信授权信息已过期，请重新授权'
                ], 400);
            }

            $wechatUserInfo = session('wechat_temp_user_info');
             $avatarService = new WechatAvatarService();

             // 准备用户数据
             $userData = [
                 'name' => $request->name,
                 'nickname' => $wechatUserInfo['nickname'],
                 'email' => $request->name . '@local.com',
                 'password' => Hash::make($request->password),
                 'email_verified_at' => now(),
                 'openid' => session('wechat_temp_openid')
             ];

             // 创建用户
             $user = User::create($userData);

             // 下载并保存微信头像
             if (!empty($wechatUserInfo['avatar'])) {
                 $localAvatarPath = $avatarService->downloadAndSaveWechatAvatar(
                     $wechatUserInfo['avatar'],
                     $user->id
                 );

                 if ($localAvatarPath) {
                     $user->update(['avatar' => $localAvatarPath]);
                 }
             }

            // 为新用户创建默认账本
            $book = $user->createDefaultBookForUser();

            // 登录用户，设置记住登录（与记住登录功能保持一致的有效期）
            Auth::login($user, true);

            // 清除临时session
            session()->forget(['wechat_temp_openid', 'wechat_temp_user_info']);

            $request->session()->regenerate();

            return response()->json([
                'success' => true,
                'message' => '注册成功！微信账号绑定完成',
                'redirect_to' => route('home')
            ]);

        } catch (\Exception $e) {
            Log::error('微信注册绑定失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '注册失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 检测是否在微信浏览器中并需要自动登录
     */
    public function checkWechatBrowser(Request $request)
    {
        // 检查是否在微信浏览器中
        $userAgent = $request->header('User-Agent');
        $isWechatBrowser = strpos($userAgent, 'MicroMessenger') !== false;

        if ($isWechatBrowser && !Auth::check()) {
            // 在微信浏览器中且未登录，跳转到微信授权登录
            return redirect()->route('wechat.login');
        }

        // 不在微信浏览器中或已登录，继续正常流程
        return redirect()->to($request->fullUrl());
    }

    public function unbind()
    {
        Auth::user()->update(['openid' => null]);
        return response()->json([
            'success' => true,
            'message' => '微信解绑成功'
        ]);
    }

    /**
     * 微信消息接收处理（异步模式）
     */
    public function handleMessage(Request $request)
    {
        $server = $this->wxapp->getServer();

        // 设置消息处理器
        $server->with(function ($message) {
            $msg = $this->processMessage($message);
            $this->sendCustomerServiceMessage($msg, $message);
            return '';
        });

        return $server->serve();
    }

    private function sendCustomerServiceMessage($content, $message)
    {
        try {
            $client = $this->wxapp->getClient();
            $response = $client->postJson('/cgi-bin/message/custom/send', [
                "touser" => $message['FromUserName'],
                "msgtype" => "text",
                "text" => [
                    "content" => $content
                ]
            ]);
            $res_str = $response->getContent();
            $res = json_decode($res_str, true);
            if ($res['errcode'] != 0) {
                Log::error('发送客服消息失败：' . $res_str);
            }
//            log_record($res);
        } catch (\Exception $e) {
            Log::error('发送客服消息失败：' . exception_to_string($e));
        }
    }

    /**
     * 预处理消息并分发异步任务
     */
    private function processMessage($message) {
        try {
            // 处理事件消息
            if ($message['MsgType'] == 'event') {
                return $this->handleEventMessage($message);
            }

            // 检查消息类型
            $supportedTypes = ['text', 'voice', 'image'];
            if (!in_array($message['MsgType'], $supportedTypes)) {
                return '暂不支持此类型消息，请发送文字、语音或图片。';
            }

            // 根据openid查找用户
            $user = User::where('openid', $message['FromUserName'])->first();

            if (!$user) {
                return '您还未绑定账户，请先在网页端登录并绑定微信。';
            }

            // 获取用户的默认账本
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return '您还没有账本，请先在网页端创建一个账本。';
            }

            // 确定使用的功能类型
            $featureType = '';
            switch ($message['MsgType']) {
                case 'text':
                    $featureType = 'record_by_text';
                    break;
                case 'voice':
                    $featureType = 'record_by_audio';
                    break;
                case 'image':
                    $featureType = 'record_by_image';
                    break;
            }

            // 检查用户是否有权限使用该功能
            if (!$user->canUseFeature($featureType)) {
                $limit = non_member_limits[$featureType] ?? 0;

                return '非会员每天只能使用'.$limit.'次'.non_member_rule_map[$featureType].'，请升级会员享受无限使用特权。\n会员权益详情：' . route('membership.benefits');
            }

            // 分发异步任务处理消息
            ProcessWechatMessageJob::dispatch($message, $user, $moneyBook);

            // 立即返回确认消息
            return '收到您的消息，正在处理中，请稍候...';

        } catch (\Exception $e) {
            Log::error('微信消息预处理失败：' . exception_to_string($e));
            return '消息处理失败，请稍后重试。';
        }
    }

    /**
     * 处理事件类型消息
     */
    private function handleEventMessage($message) {
        try {
            switch ($message['Event']) {
                case 'subscribe':
                    // 用户关注
                    return $this->handleSubscribeEvent($message);
                case 'unsubscribe':
                    // 用户取消关注，可以在这里做一些清理工作
                    Log::info('用户取消关注：' . $message['FromUserName']);
                    return '';
                case 'CLICK':
                    // 处理菜单点击事件
                    return $this->handleMenuClickEvent($message);
                default:
                    return '';
            }
        } catch (\Exception $e) {
            Log::error('处理事件消息失败：' . exception_to_string($e));
            return '事件处理失败，请稍后重试。';
        }
    }

    /**
     * 处理用户关注事件
     */
    private function handleSubscribeEvent($message) {
        $welcomeMessage = <<<EOT
Hi～我是你的AI记账管家！🤖
你只需输入或说出花费内容，比如 「打车30」「昨天吃饭50」，我就能自动帮你归类记录📝
你也可以上传消费小票、消费截图快速记账

👉 首次使用请先点击菜单栏注册并绑定微信
👉 点击菜单栏「免费领取」可获得7天会员体验
EOT;

        return $welcomeMessage;
    }

    /**
     * 处理菜单点击事件
     */
    private function handleMenuClickEvent($message) {
        // 根据EventKey判断点击的是哪个菜单
        switch ($message['EventKey']) {
            case 'GET_FREE_MEMBERSHIP':
                return $this->handleFreeMembershipEvent($message);
            default:
                return '功能开发中，敬请期待！';
        }
    }

    /**
     * 处理免费领取会员事件（异步处理）
     */
    private function handleFreeMembershipEvent($message) {
        try {
            // 将免费会员处理任务加入队列异步处理
            ProcessFreeMembershipJob::dispatch($message['FromUserName']);
            return '正在为您处理免费会员领取，请稍等片刻...';
        } catch (\Exception $e) {
            Log::error('分发免费会员处理任务失败：' . exception_to_string($e));
            return '系统繁忙，请稍后重试。';
        }
    }

    /**
     * 创建微信菜单
     */
    public function createMenu()
    {
        try {
            $buttons = $this->getMenuButtons();

            $client = $this->wxapp->getClient();
            $response = $client->postJson('/cgi-bin/menu/create', [
                'button' => $buttons
            ]);

            $result = json_decode($response->getContent(), true);

            if ($result['errcode'] === 0) {
                return response()->json([
                    'success' => true,
                    'message' => '微信菜单创建成功'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => '微信菜单创建失败：' . $result['errmsg']
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error('创建微信菜单失败：' . exception_to_string($e));
            return response()->json([
                'success' => false,
                'message' => '创建微信菜单失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取菜单按钮配置
     *
     * @return array
     */
    private function getMenuButtons()
    {
        return [
            [
                "name" => "记账助手",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "系统首页",
                        "url" => route('home')
                    ],
                    [
                        "type" => "view",
                        "name" => "登录/注册",
                        "url" => route('login')
                    ],
                    [
                        "type" => "click",
                        "name" => "领取7天会员",
                        "key" => "GET_FREE_MEMBERSHIP"
                    ]
                ]
            ],
            [
                "type" => "view",
                "name" => "记一笔",
                "url" => route('transaction.create')
            ],
            [
                "name" => "我的",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "个人中心",
                        "url" => route('user.profile')
                    ],
                    [
                        "type" => "view",
                        "name" => "会员中心",
                        "url" => route('membership.benefits')
                    ],
                    [
                        "type" => "view",
                        "name" => "统计分析",
                        "url" => route('statistics.index')
                    ],
                    [
                        "type" => "view",
                        "name" => "交易明细",
                        "url" => route('details.index')
                    ]
                ]
            ]
        ];
    }
}
